package czk.concrent.reentrantLock.wheellock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 一：时程序中出现了线程相互等待，并尝试获取对方（锁）资源的情况，这就是典型的死锁问题了。
 * 死锁问题的演示
 *
 * @Author:ChenZhangKun
 * @Date: 2021/8/31 10:03
 */
public class Demo1 {
    public static void main(String[] args) {
        // 定义锁
        Lock lock1 = new ReentrantLock();
        Lock lock2 = new ReentrantLock();

        new Thread(() -> {
            try {
                lock1.lock();
                System.out.println("线程一获取到锁：A");
                // 获取锁二
                Thread.sleep(1000);
                System.out.println("线程一等待获取锁：B");
                try {
                    lock2.lock();
                    System.out.println("线程一获取到了锁：B");
                } finally {
                    lock2.unlock();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
            }
        }).start();

        new Thread(() -> {
            try {
                lock2.lock();
                System.out.println("线程二获取到锁：B");
                // 获取锁二
                Thread.sleep(1000);
                System.out.println("线程二等待获取锁：A");
                try {
                    lock1.lock();
                    System.out.println("线程二获取到了锁：A");
                } finally {
                    lock1.unlock();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock2.unlock();
            }
        }).start();
    }
}
